<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/8
 * Time: 16:53
 */

namespace Common\Model;


use Think\Model;

class MailListModel extends Model
{
    protected $_auto = array(
        array('add_time','time_format', self::MODEL_INSERT, 'function', NOW_TIME),
        array('update_time', 'time_format',self::MODEL_BOTH, 'function', NOW_TIME),
        array('state', 1),
    );



    /**
     * 更新或者添加通讯录
     * @param null $data
     * @return bool|null
     */
    public function update($data = null){
        $data = $this->token(false)->create($data);
        if (empty($data)){
            return false;
        }

        if (empty($data['mail_list_id'])){
            $id = $this->add();
            if (!$id){
                $this->error = '新增通讯录出错';
                return false;
            }
            $data['mail_list_id'] = $id;
        }else{
            $status = $this->save();
            if (false === $status){
                $this->error = '更新通讯录出错';
                return false;
            }
        }
        $data['icon'] = $this->checkIcon($data['mail_list_id']);
        return $data;
    }

    public function checkIcon($id){
        $data = $this->find($id);
        if($data['sex'] == 0 && $data['icon'] == C('DEFAULT_MAILLIST_ICON.MALE')){
            return $data['icon'];
        }
        if($data['sex'] == 1 && $data['icon'] == C('DEFAULT_MAILLIST_ICON.FEMALE')){
            return $data['icon'];
        }
        if(empty($data['icon'])){
            if($data['sex'] == 0){
                $data['icon'] = C('DEFAULT_USER_ICON.MALE');
            }else{
                $data['icon'] = C('DEFAULT_USER_ICON.FEMALE');
            }
            $this->save($data);
            return $data['icon'];
        }else{
            $to = $id . '_' . time();
            if(renameFile(false, $data['icon'], $to )){
                $data['icon'] = $to;
                $this->save($data);
                return $to;
            }else{
                return $data['icon'];
            }
        }

    }


    /**
     * 删除通讯录并不是真删除
     * @param array|mixed $mail_list_id
     * @return bool
     */
    public function delete($mail_list_id){
        $map['mail_list_id'] = $mail_list_id;
        $res = $this->where($map)->setField('status', 0);
        return $res !== false;
    }


}